package com.dsj.gxrd.utils;

import com.dsj.gxrd.common.MyBaseEntity;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.system.api.model.LoginUser;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.LocalDateTime;

/**
 * @author songpin566
 * @date 2023/09/22
 **/
public class BaseEntityHandlerUtils {


    public static <T> void fastSetBaseEntity(MyBaseEntity<T> t, LoginUser user) {
        Class<?> superclass1 = t.getClass().getSuperclass();
        try {
            Type superclass = t.getClass().getGenericSuperclass();
            ParameterizedType a = (ParameterizedType) superclass;
            Type actualTypeArgument = a.getActualTypeArguments()[0];
            Class<?> type = (Class<?>) actualTypeArgument;
            Field[] declaredFields = superclass1.getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                if (field.getName().equals(Constants.CREATE_BY) || field.getName().equals(Constants.UPDATE_BY)) {
                    if (String.class.isAssignableFrom((type))) {
                        field.set(t, user.getSysUser().getUserName());
                    } else if (Long.class.isAssignableFrom(type)) {
                        field.set(t, user.getSysUser().getUserId());
                    } else if (Integer.class.isAssignableFrom(type)) {
                        field.set(t, user.getSysUser().getUserId().intValue());
                    }
                } else {
                    field.set(t, LocalDateTime.now());
                }

            }

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

}
